<?php

declare(strict_types=1);

namespace app\admin\model\auth;

use sheep\model\auth\Admin as BaseAdmin;

class Admin extends BaseAdmin
{
    protected $name = 'admin';

    protected $type = [
        'role_id'     => 'integer',
        'login_time'  =>  'timestamp',
    ];

    protected $json = [];    // 自动 json 转换


    // 模型事件写入前
    public static function onBeforeWrite($admin)
    {
        $input_password = request()->param('password');
        if ($input_password && in_array(request()->action(), ['add', 'edit'])) {      // 包含管理员添加编辑，和编辑自己资料
            // 每次修改密码，都重新生成 salt
            $salt = mt_rand(1000, 9999);
            $admin->salt = $salt;
            $admin->password = (new static)->encryptPassword($input_password, $salt);
        }
    }

    public function role()
    {
        return $this->hasOne("Role", "id", "role_id")->field("id, name");
    }
}
